package cn.congine.wizarpos.mall.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.congine.wizarpos.mall.common.RespMessage;
import cn.congine.wizarpos.mall.model.open.DelShoppingCartItemInput;
import cn.congine.wizarpos.mall.model.open.DelShoppingCartItemOutput;
import cn.congine.wizarpos.mall.model.open.GetShoppingCartInput;
import cn.congine.wizarpos.mall.model.open.GetShoppingCartOutput;
import cn.congine.wizarpos.mall.model.open.ShoppingCartIsEmptyInput;
import cn.congine.wizarpos.mall.model.open.ShoppingCartIsEmptyOutput;
import cn.congine.wizarpos.mall.model.open.UpdateShoppingCartItemNumInput;
import cn.congine.wizarpos.mall.model.open.UpdateShoppingCartItemNumOutput;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.Utils;
import cn.congine.wizarpos.mall.vo.WxShoppingCartItem;

@Controller
@RequestMapping(value = "/wx_shopping_cart")
public class WxShoppingCartAction {
	
	private static Logger logger = Logger.getLogger(WxShoppingCartAction.class);

	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;

	/**
	 * 购物车明细
	 * @param openId
	 * @param mid
	 * @return
	 * @author xudongdong
	 */
	@RequestMapping(value = "/get_cart_list")
	public ModelAndView getShoppingCart(
			@RequestParam(value = "mid") String mid,
			HttpServletRequest httpRequest) {
		Map<String, Object> data = new HashMap<String, Object>();		
		Map<String, Object> qtys = new HashMap<String, Object>();// 保存购物商品数量的集合
		Map<String, Object> names = new HashMap<String, Object>();// 商品名字集合
		Map<String, Object> pictures = new HashMap<String, Object>();// 商品图片集合

		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(cardId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		
		GetShoppingCartInput input = new GetShoppingCartInput();
		input.setMid(mid);
		input.setCardId(cardId);
		GetShoppingCartOutput output = (GetShoppingCartOutput) wizarposOpenRestClient.post(input, "/wxshop/get_cart_list", GetShoppingCartOutput.class);								
		
		if (output == null || "60001".equals(output.getCode())) {//非法慧商户
			return new ModelAndView("error").addObject("err_message",
					"系统错误");
		} else if ("60070".equals(output.getCode())) {//60070 此商户下不存在此会员	
			return new ModelAndView("redirect:/vip/receiveCard?mid=" + mid);//前往会员卡领取页面
		}
		
		// 获取购物车里的商品信息
		List<WxShoppingCartItem> item = output.getWxShoppingCartItemList();
		
		double num = 0;// 单价
		int in = 0;// 计数
		if (item != null) {
			for (WxShoppingCartItem it : item) {
				Integer qty = it.getProductNum();
				in = in + 1;
				if (it.getPicUrl() == null) {
					pictures.put(it.getId(), SysConstants.DEFAULT_PICTURE);
				} else {
					pictures.put(it.getId(), Function.dealGridPicUrl(it.getPicUrl(), 300, 300));
				}
				num += it.getProductPrice() * it.getProductNum();			
				it.setShowPrice(it.getShowPrice());
				qtys.put(it.getId(), qty);
				String prtName = it.getProductName();
				names.put(it.getId(), prtName.length() > 20 ? 
						prtName.substring(0,20)+"..." 
						: prtName);
			}
		}
		data.put("in", in);
		data.put("mid", mid);
		data.put("item", item);
		data.put("cartId", output.getCartId());		
		data.put("qtys", qtys);
		data.put("names", names);
		data.put("pictures", pictures);
		data.put("num", Utils.formatAmount(num));
		return new ModelAndView("shoppingcat/shoppingcart", data);
	}	
	
	/**
	 * 购物车商品数量修改
	 * @param itemId
	 * @param num
	 * @return
	 * @author xudongdong
	 */
	@RequestMapping(value = "/update_item_num")
	@ResponseBody
	public RespMessage updateItemNum(
			@RequestParam(value = "itemId") String itemId,
			@RequestParam(value = "num") Integer num) {
		RespMessage res = new RespMessage();		
		UpdateShoppingCartItemNumInput input = new UpdateShoppingCartItemNumInput();
		input.setItemId(itemId);
		input.setNum(num.toString());
		UpdateShoppingCartItemNumOutput output = (UpdateShoppingCartItemNumOutput) wizarposOpenRestClient.post(input, "/wxshop/update_item_num", UpdateShoppingCartItemNumOutput.class);				
		if (output == null) {//请求开发平台出错
			res.setCode(1);
			res.setMessage("系统错误，请联系商家");
			return res;
		} else if ("60039".equals(output.getCode()) || output.getWxShoppingCartItemList() == null) {//非法购物车条目或购物车为空
			res.setCode(Integer.valueOf(output.getCode()));
			res.setMessage("购物车为空，请刷新");
			return res;
		} else if ("60040".equals(output.getCode())) {//非法的购物车条目数量
			res.setCode(Integer.valueOf(output.getCode()));
			res.setMessage("购物车数量非法，请刷新");
			return res;			
		}
		List<cn.congine.wizarpos.mall.vo.WxShoppingCartItem> list = output.getWxShoppingCartItemList();
		int sum = 0;
		for (WxShoppingCartItem it : list) {
			sum += it.getProductPrice() * it.getProductNum();
		}
		res.setObj(Utils.formatAmount(sum));
	    return res;
	}		
	
	/**
	 * 购物车商品删除
	 * @param openId
	 * @param itemId
	 * @param mid
	 * @return
	 * @author xudongdong
	 */
	@RequestMapping(value = "/del_cart_item")
	@ResponseBody
	public RespMessage delWxShoppingCartItem(
			@RequestParam(value = "itemId") String itemId,
			@RequestParam(value = "mid") String mid) {
		RespMessage res = new RespMessage();

		DelShoppingCartItemInput input = new DelShoppingCartItemInput();
		input.setMid(mid);
		input.setItemId(itemId);		
		DelShoppingCartItemOutput output = (DelShoppingCartItemOutput) wizarposOpenRestClient.post(input, "/wxshop/del_cart_item", DelShoppingCartItemOutput.class);					
		
		if (output != null && "0".equals(output.getCode())) {//操作成功
			res.setCode(0);
			return res;			
		} else {//删除失败
			res.setCode(1);
			return res;			
		}
	}	
	
	/**
	 * 购物车是否存在
	 * @param openId
	 * @param mid
	 * @return
	 * @author xudongdong
	 */
	@RequestMapping(value = "/isEmpty")
	public @ResponseBody RespMessage isEmpty(
			@RequestParam(value = "mid") String mid,
			HttpServletRequest httpRequest) {
		RespMessage res = new RespMessage();
		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(cardId)) {//session过期，跳转到登录注册页面
			res.setCode(2);
			return res;
		}			
		ShoppingCartIsEmptyInput input = new ShoppingCartIsEmptyInput();
		input.setMid(mid);
		input.setCardId(cardId);
		ShoppingCartIsEmptyOutput output = (ShoppingCartIsEmptyOutput) wizarposOpenRestClient.post(input, "/wxshop/isEmpty", ShoppingCartIsEmptyOutput.class);

		if ("-1".equals(output.getOutCode())) {//购物车为空
			res.setCode(1);
			return res;
		}
		res.setCode(0);
		return res;		
	}	
}
